<template>
  <div class="bk-switch" :class="switchClass" :style="switchStyle" @click="handleClick">
    <div class="bk-switch__node">
      <loading v-if="loading" color="" />
    </div>
  </div>
</template>

<script>
import loading from 'components/loading/icon'

export default {
  name: 'bk-switch',
  props: {
    value: {
      type: Boolean,
      required: true
    },
    disabled: {
      type: Boolean,
      default: false
    },
    loading: Boolean,
    size: [String, Number]
  },
  methods: {
    handleClick (e) {
      if (this.disabled) return
      this.$emit('input', !this.value)
      this.$emit('click', e)
    }
  },
  watch: {
    value (value) {
      this.$emit('change', value)
    }
  },
  computed: {
    switchClass () {
      return {
        checked: this.value,
        disabled: this.disabled
      }
    },
    switchStyle () {
      return {
        fontSize: this.size ? this.size.toString().includes('px') ? this.size : this.size + 'px' : null
      }
    }
  },
  components: { loading }
}
</script>

<style scoped lang="less">
@import "~common/style/variable.less";

.bk-switch {
  position: relative;
  display: inline-block;
  box-sizing: content-box;
  width: 2em;
  height: 1em;
  font-size: 30px;
  background-color: #fff;
  border: 1px solid rgba(0,0,0,.1);
  border-radius: 1em;
  cursor: pointer;
  transition: background-color .3s;
  .bk-switch__node {
    position: absolute;
    top: 0;
    left: 0;
    width: 1em;
    height: 1em;
    font-size: inherit;
    background: #fff;
    border-radius: 100%;
    box-shadow:
      0 3px 1px 0 rgba(0,0,0,.05),
      0 2px 2px 0 rgba(0,0,0,.1),
      0 3px 3px 0 rgba(0,0,0,.05);
    transition:
      transform .3s cubic-bezier(0.3, 1.05, 0.4, 1.05),
      -webkit-transform .3s cubic-bezier(0.3, 1.05, 0.4, 1.05);

    .loading {
      width: 50%;
      height: 50%;
      position: relative;
      top: 25%;
      left: 25%;
      color: @color-theme;
      display: block;
    }
  }
}

.bk-switch.checked {
  background: @color-theme;
  .bk-switch__node {
    transform: translateX(1em);
  }
}
.bk-switch.disabled {
  cursor: not-allowed;
  opacity: .5;
}
</style>
